<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const showLoginDialog = ref(false)
const username = ref('')
const loginType = ref < 'user' | 'customer' > ('user')

async function handleLogin() {
    try {
        if (loginType.value === 'user') {
            const { data } = await axios.post('http://127.0.0.1:8000/api/user/login/', {username:username.value})
            userStore.setUser({ username: username.value, uuid: data.uuid })
            router.push('/chatuser')
        } else {
            await axios.post('http://127.0.0.1:8000/api/customer_service/login/', { username: username.value })
            userStore.setUser({ username: username.value, isCustomerService: true })
            router.push('/chatservice')
        }
        showLoginDialog.value = false
    } catch (error) {
        ElMessage.error('登录失败')
    }
}
</script>

<template>
    <div class="home">
        <h1>在线客服系统</h1>
        <div class="buttons">
            <el-button type="primary" @click="() => { loginType = 'user'; showLoginDialog = true }">
                在线咨询
            </el-button>
            <el-button @click="() => { loginType = 'customer'; showLoginDialog = true }">
                客服入口
            </el-button>
        </div>

        <el-dialog v-model="showLoginDialog" :title="loginType === 'user' ? '用户登录' : '客服登录'" width="30%">
            <el-form>
                <el-form-item label="用户名">
                    <el-input v-model="username" placeholder="请输入用户名" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showLoginDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleLogin">登录</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped>
.home {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;

    h1 {
        margin-bottom: 2rem;
    }

    .buttons {
        display: flex;
        gap: 1rem;
    }
}
</style>